import {
	delectFile,
	downloadFile,
	getDownloadList,
	uploadFile,
} from "@/utils/cos";
import { Button, message, Progress, Radio, Spin, Upload } from "antd";
import { useEffect, useState } from "react";

/**
 * getDownloadList 获取下载列表
 * uploadFile 上传文件
 * downloadFile 下载文件
 * delectFile 删除文件
 */
function App() {
	const [loading, setLoading] = useState(false); // 加载
	const [progress, setProgress] = useState(0); // 进度条
	const [list, setList] = useState([]); // 文件列表
	const [flieName, setFlieName] = useState(""); // 文件名称

	const props = {
		action: "",
		headers: { authorization: "authorization-text" },
		showUploadList: false,
		beforeUpload(file) {
			// 判断是否存在相同的名称
			const isExist = list.some(item => item.value === file.name);
			if (isExist) message.error("文件已存在");
			!isExist && setLoading(true);
			return !isExist;
		},
		onChange({ file }) {
			// 设置进度条
			const callback = v => {
				setProgress(+v);
			};
			if (file.status === "done") {
				uploadFile(file.originFileObj, file.name, callback)
					.then(() => {
						message.success("上传成功");
						getDate();
					})
					.finally(() => {
						setLoading(false);
					});
			}
		},
	};
	const onChange = e => {
		setFlieName(e.target.value);
	};
	const onDownload = () => {
		if (!flieName) return message.error("请选择文件");
		downloadFile(flieName);
	};

	// 请求接口
	useEffect(() => {
		getDate();
	}, []);

	// 查询
	const getDate = () => {
		getDownloadList().then(res => {
			setList(res);
		});
	};
	// 清空
	const onClear = () => {
		if (!flieName) return message.error("请选择文件");
		delectFile(flieName).then(() => {
			message.success("删除成功");
			getDate();
			setFlieName("");
		});
	};

	return (
		<Spin spinning={loading}>
			<div className="flex gap-2 mt-2 pl-2">
				<Upload {...props}>
					<Button>上传</Button>
				</Upload>
				<Button className="block" onClick={getDate}>
					查询
				</Button>
				<Button className="block" onClick={onDownload}>
					下载
				</Button>
				<Button className="block" onClick={onClear}>
					删除
				</Button>
			</div>
			<div style={{ width: "200px" }}>
				{!!progress && <Progress percent={progress} />}
			</div>
			{list.length ? (
				<Radio.Group
					className="grid gap-2 mt-2 pl-2"
					options={list}
					onChange={onChange}
				/>
			) : (
				<div>暂无数据</div>
			)}
		</Spin>
	);
}
export default App;
